import axios from 'axios';
import { Message } from 'element-ui'; // 引入element-ui的消息提示组件，用于提示接口的报错等
import { Toast } from 'vant';//引入vant的消息提示组件，用于提示接口的报错等
import store from '../store/index'; // 引入vuex-store
import router from '../router/index'


// 创建axios实例
axios.defaults.withCredentials = true;
const httpService = axios.create({
    baseURL: "/api", // 自定义，url前缀-'http:xxx.xxx'
    timeout: 8000, // 自定义请求超时时间
    withCredentials: false, // `withCredentials` 表示跨域请求时是否需要使用凭证
});


// 跳转登录页方法，携带当前页面路由，以期在登录页面完成登录后返回当前页面
const toLogin = () => {
    router.replace({
        path: '/login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    });
}

const to404 = () => {
    router.replace({
        path: '/404',
        query: {
            redirect: router.currentRoute.fullPath
        }
    });
}


// request拦截器，添加请求拦截器，若token存在则在请求头中加token，不存在也继续请求
httpService.interceptors.request.use(
    config => {
        if (store.state.token) {
            console.log("请求token：" + store.state.token);
            // config.headers['token'] = store.state.token // 让每个请求携带自定义token，根据实际情况自行修改
            // config.headers['token'] = store.getters.get_token;
            config.headers['Authorization'] = store.getters.get_token
        }
        return config;
    },
    error => {
        // 请求错误处理
        console.log("在request拦截器显示错误：", error.response)
        return Promise.reject(error);
    }
)

// respone拦截器
httpService.interceptors.response.use(
    //请求成功
    response => {
        if (response.status === 200) {
            // 统一处理状态
            return Promise.resolve(response);
        } else if (response.status === 401) {
             MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                store.dispatch('LogOut').then(() => {
                    location.href = '/index';
                })
            })
        } else {
            return Promise.reject(response)
        }
    },
    //请求失败,对状态码做处理
    error => {
        if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    error.message = '错误请求';
                    to404();
                    break;

                case 401:
                    error.message = '未授权，请重新登录';
                    store.commit("del_token"); //可能是token过期，清除它
                    toLogin();//跳转到登陆页面
                    break;

                case 403:
                    error.message = '拒绝访问';
                    to404();
                    break;

                case 404:
                    error.message = '请求错误,未找到该资源';
                    to404();
                    break;

                case 500:
                    error.message = '服务器端出错';
                    to404();
                    break;

                default:
                    error.message = `未知错误${error.response.status}`;
                    to404();
            }
            console.log(error.message)
            // Message.error(error.message)

        } else {
            error.message = "连接服务器失败";
            to404();
            // Message.error(error.message)
        }
        return Promise.reject(error);
    }
)

// 网络请求部分

// get请求，url:请求地址，params:参数
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

//  post请求，url:请求地址，params:参数
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService.post(url, params)
            .then(response => {
                resolve(response);
            })
            .catch(error => {
                reject(error);
            })
        // httpService({
        //     url: url,
        //     method: 'post',
        //     data: params
        // }).then(response => {
        //     resolve(response);
        // }).catch(error => {
        //     reject(error);
        // });
    });
}

// delete请求，url:请求地址，params:参数
export function del(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService.delete(url, {
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

// delete请求体，url:请求地址，params:参数
export function delc(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService.delete(url, {
            data: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

// put请求，url:请求地址，params:参数
export function put(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService.put(url, params)
            .then(response => {
                resolve(response);
            })
            .catch(error => {
                reject(error);
            })
    });
}

//  文件上传，url:请求地址，params:参数
export function upload(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export default {
    get,
    del,
    delc,
    post,
    put,
    upload
}


// 没有封装api方法，使用方法
// 在 main.js 文件里引用 https
// import http from '@/api/https.js'
// Vue.prototype.$http = http

// 页面调用
// this.$http.get(url, { custcode: "" }).then(res =>{})
// this.$http.post(url, { data }).then(res =>{})
// this.$http.put(url, { data }).then(res =>{})
// this.$http.del(url, { id: "" }).then(res =>{})